<?php
/**
 * Created by PhpStorm.
 * User: buddha
 * Date: 2021/6/17
 * Time: 18:46
 */

namespace app\admin\controller;


use app\admin\service\RoleAuthService;
use app\BaseController;

class RoleAuth extends BaseController
{
    /**
     * @var $service RoleAuthService
     */
    protected $service;

    public function initialize()
    {
        parent::initialize();
        $this->service = new RoleAuthService();
    }

    /**
     * 通过角色id获取权限id
     * @param $id
     * @return \think\response\Json
     */
    public function read($id) {
        $result = $this->service->getAuthIdByRoleId($id);
        return success('ok', $result);
    }

    /**
     * 给角色设置权限
     * @param $id
     * @return \think\response\Json
     */
    public function update($id) {
        // 请求auth_id
        $requestGetAuthIds = explode(',', request()->data->auth_id);
        // 查询auth_id
        $selectGetAuthIds = $this->service->getAuthIdByRoleId($id);
        // 需要写入数据库
        $write = array_diff($requestGetAuthIds, $selectGetAuthIds);
        if ($write) {
            // 写入逻辑
            $this->service->setAuthToRole($id, $write);
        }
        // 需要删除数据库
        $delete = array_diff($selectGetAuthIds, $requestGetAuthIds);
        if ($delete) {
            // 删除逻辑
            $this->service->deleteAuthToRole($id, $delete);
        }
        return success('权限设置成功');
    }
}
